//
//  CZAddContactViewController.m
//  XMPP项目练习
//
//  Created by 盛 发 况 on 16/5/5.
//  Copyright © 2016年 盛 发 况. All rights reserved.
//

#import "CZAddContactViewController.h"
#import "CZXMPPTools.h"

@interface CZAddContactViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *nameText;

@end

@implementation CZAddContactViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"新建联系人";
}

// 在文本框上按回车
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    // 添加好友
    if (textField.text.length > 0) {
        [self addFriendWithName:textField.text];
    }
    
    return YES;
}

// 添加好友
- (void)addFriendWithName:(NSString *)name {
    
    // 判断name中是否包含域名
    NSRange range = [name rangeOfString:@"@"];
    DDLogInfo(@"%zd",range.location);
    if (range.location == NSNotFound) {
        name = [name stringByAppendingFormat:@"@%@",[CZXMPPTools sharedXMPPTools].xmppStream.myJID.domain];
    }
    DDLogInfo(@"%@", name);

    XMPPJID *jid = [XMPPJID jidWithString:name];
    // 如果已经是我的好友，就不再需要发送订阅请求（添加好友的请求）
    if ([[CZXMPPTools sharedXMPPTools].xmppRosterCoreDataStorage userExistsWithJID:jid xmppStream:[CZXMPPTools sharedXMPPTools].xmppStream]) {
        
        [[[UIAlertView alloc]initWithTitle:@"提示" message:@"已经是好友，无需添加" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil] show];
        
        return;
    }
    
    // 添加订阅
    [[CZXMPPTools sharedXMPPTools].xmppRoster subscribePresenceToUser:jid];
    
    [self.navigationController popViewControllerAnimated:YES];
}


@end



